package com.cennavi.bigdata.baotou.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.cennavi.bigdata.baotou.dao.ImportDao;
import com.cennavi.bigdata.baotou.entities.RoadPieDataNew;
import com.cennavi.bigdata.baotou.service.ImportService;
import com.cennavi.bigdata.baotou.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

/**
 * Created by cennavi on 2018/10/23.
 */
@Service
public class ImportServiceImpl implements ImportService {

    @Autowired
    private ImportDao importDao;

    @Override
    public int saveRoad_Piecewise_Data(MultipartFile file) {

        //道路id跟名称对应关系
        JSONObject commJson = importDao.getRoadId_NameJson();
        //生成基础表信息，入库
        List<JSONObject> roadList =  listRoad_Piecewise_Data(commJson,file);
        //基础路段数据入库
        return importDao.saveRoad_Piecewise_Data(roadList);
//        return 0;
    }

    @Override
    public String saveRoad_Piecewise_Data_New_T(MultipartFile file) {
        //道路id跟名称对应关系
        JSONObject commJson = importDao.getRoadId_NameJson();
        //道路分组
        List<List<String>> lists = groupByRoad(file);
        //切分组合数据
        Map<String,Object> map = makeRoadPieDataNew(lists,commJson);
        List<RoadPieDataNew> roadPieNewList = (List<RoadPieDataNew>) map.get("RoadPieDataNew");
        List<Map<String,Object>> roadids = (List<Map<String, Object>>) map.get("roadids");

        //保存生成的新的路段信息
        int roadcount = importDao.saveRoadPieNewList(roadPieNewList);

        //保存新的路段跟原有路段的关系
        int idCount = importDao.saveRoadids(roadids);

        String count = roadcount +","+ idCount;

        return count;
    }

    private Map<String, Object> makeRoadPieDataNew(List<List<String>> lists, JSONObject commJson) {
        Map<String, Object> map = new HashMap<>();
        try {
            List<RoadPieDataNew> roadPieNewList = new ArrayList<>();
            List<Map<String, Object>> maps = new ArrayList<Map<String, Object>>();
            //遍历分组后的数据，进行路段的分割，重组（生成整合后的路段id，以及和基础路段的id的对应关系）
            for (List<String> list : lists) {

                //整段数据组合
                String[] split_0 = list.get(0).split(",");
                String[] split_last = list.get(list.size() - 1).split(",");
                String roadname = split_0[1]+"-"+split_0[5]+"到"+split_last[6]+split_0[3];//路段名称
                String id = StringUtil.getPY(roadname);//生成的路段id
                String kind =split_0[7].charAt(6)+"";//道路等级
                String dir = split_0[3];//方向
                double length = 0.0;//路段总长度
                for (int i = 0; i < list.size(); i++) {
                    Map<String, Object> idmap = new HashMap<>();
                    String[] split = list.get(i).split(",");
                    length += Double.valueOf(split[8]);
                    String name = split[1]+"("+split[5]+","+split[6]+")";
                    idmap.put("id",id);
                    idmap.put("roadid",commJson.getString(name));
                    maps.add(idmap);
                }
                //计算最大最小旅行时间
                double minTraveltime=0.0;
                double maxTraveltime=0.0;
                if (kind.equals("1")||kind.equals("2")||kind.equals("3")||kind.equals("4")){//min 8，max 70 速度
                    minTraveltime = (length*1000)/(70/3.6);
                    maxTraveltime = (length*1000)/(8/3.6);
                }else {//min 5 ，max 60 速度
                    minTraveltime = (length*1000)/(60/3.6);
                    maxTraveltime = (length*1000)/(5/3.6);
                }
                RoadPieDataNew roadPieDataNew = new RoadPieDataNew();
                roadPieDataNew.setROADID(id);
                roadPieDataNew.setKIND(kind);
                roadPieDataNew.setROADLENGTH(length);
                roadPieDataNew.setROADNAME(roadname);
                roadPieDataNew.setROADDIRECTION(dir);
                roadPieDataNew.setMAXTRAVELTIME(maxTraveltime);
                roadPieDataNew.setMINTRAVELTIME(minTraveltime);
                roadPieNewList.add(roadPieDataNew);
                //需要分段路段数据整合，对路进行分段，共三段
                if (list.size()>3){
                    String[] split_mid = list.get(list.size()/2 - 1).split(",");
                    String roadname_1 = split_0[1]+"-"+split_0[5]+"到"+split_mid[6]+split_0[3];//路段名称
                    String roadname_2 = split_mid[1]+"-"+split_mid[5]+"到"+split_last[6]+split_0[3];//路段名称
                    String id_1 = StringUtil.getPY(roadname_1);//生成的路段id
                    String id_2 = StringUtil.getPY(roadname_2);//生成的路段id
                    double length_1 = 0.0;//路段总长度
                    double length_2 = 0.0;//路段总长度
                    for (int i = 0; i < list.size() / 2; i++) {
                        Map<String, Object> idmap = new HashMap<>();
                        String[] split = list.get(i).split(",");
                        length_1 += Double.valueOf(split[8]);
                        String name = split[1]+"("+split[5]+","+split[6]+")";
                        idmap.put("id",id_1);
                        idmap.put("roadid",commJson.getString(name));
                        maps.add(idmap);
                    }
                    for (int i = list.size()/2; i < list.size(); i++) {
                        Map<String, Object> idmap = new HashMap<>();
                        String[] split = list.get(i).split(",");
                        length_2 += Double.valueOf(split[8]);
                        String name = split[1]+"("+split[5]+","+split[6]+")";
                        idmap.put("id",id_2);
                        idmap.put("roadid",commJson.getString(name));
                        maps.add(idmap);
                    }
                    //计算最大最小旅行时间
                    double minTraveltime_1=0.0;
                    double maxTraveltime_1=0.0;
                    double minTraveltime_2=0.0;
                    double maxTraveltime_2=0.0;
                    if (kind.equals("1")||kind.equals("2")||kind.equals("3")||kind.equals("4")){//min 8，max 70 速度
                        minTraveltime_1 = (length_1*1000)/(70/3.6);
                        maxTraveltime_1 = (length_1*1000)/(8/3.6);
                        minTraveltime_2 = (length_2*1000)/(70/3.6);
                        maxTraveltime_2 = (length_2*1000)/(8/3.6);
                    }else {//min 5 ，max 60 速度
                        minTraveltime_1 = (length_1*1000)/(60/3.6);
                        maxTraveltime_1 = (length_1*1000)/(5/3.6);
                        minTraveltime_2 = (length_2*1000)/(60/3.6);
                        maxTraveltime_2 = (length_2*1000)/(5/3.6);
                    }
                    RoadPieDataNew roadPieDataNew_1 = new RoadPieDataNew();
                    roadPieDataNew_1.setROADID(id_1);
                    roadPieDataNew_1.setKIND(kind);
                    roadPieDataNew_1.setROADLENGTH(length_1);
                    roadPieDataNew_1.setROADNAME(roadname_1);
                    roadPieDataNew_1.setROADDIRECTION(dir);
                    roadPieDataNew_1.setMAXTRAVELTIME(maxTraveltime_1);
                    roadPieDataNew_1.setMINTRAVELTIME(minTraveltime_1);
                    roadPieNewList.add(roadPieDataNew_1);

                    RoadPieDataNew roadPieDataNew_2 = new RoadPieDataNew();
                    roadPieDataNew_2.setROADID(id_2);
                    roadPieDataNew_2.setKIND(kind);
                    roadPieDataNew_2.setROADLENGTH(length_2);
                    roadPieDataNew_2.setROADNAME(roadname_2);
                    roadPieDataNew_2.setROADDIRECTION(dir);
                    roadPieDataNew_2.setMAXTRAVELTIME(maxTraveltime_2);
                    roadPieDataNew_2.setMINTRAVELTIME(minTraveltime_2);
                    roadPieNewList.add(roadPieDataNew_2);
                }
            }
            map.put("RoadPieDataNew",roadPieNewList);
            map.put("roadids",maps);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 对路段进行分组
     * @param file
     * @return
     */
    private List<List<String>> groupByRoad(MultipartFile file) {
        BufferedReader reader = null;
        List<List<String>> lists = new ArrayList<>();
        try {
            //对路段数据进行分组
            reader = new BufferedReader(new InputStreamReader(file.getInputStream(), "UTF-8"));
            String line ;
            int count = -1;
            while ((line=reader.readLine()) != null){
                line = line.replaceAll("\"", "");
                String[] split = line.split(",");
                if (!split[1].contains("辅路")){
                    if (split[4].equals("0")){
                        List<String> listStr = new ArrayList<>();
                        listStr.add(line);
                        lists.add(listStr);
                        count++;
                    }else {
                        lists.get(count).add(line);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (reader !=null){
                try {
                    reader.close();
                }catch (Exception e1){
                    e1.getMessage();
                }
            }
        }
        return lists;
    }

    @Override
    public int insertToPgRoadGeomtry(List<Map<String, Object>> list) {

        return importDao.insertToPgRoadGeomtry(list);
    }

    /**
     * 获取带有id的基础路段数据
     * @param commJson
     * @param file
     * @return
     */
    private List<JSONObject> listRoad_Piecewise_Data(JSONObject commJson, MultipartFile file) {

        BufferedReader reader = null;
        List<JSONObject> list = new ArrayList<>();
        try {
            reader = new BufferedReader(new InputStreamReader(file.getInputStream(), "UTF-8"));
            String line;
            while ((line = reader.readLine())!=null){
                String[] split =  line.replaceAll("\"","").split(",");
                String roadapplication = split[1] + "(" +split[5] + "," + split[6] + ")";//路段名称
                if (split[9].split(";").length>1&&commJson.containsKey(roadapplication)){
                    String roadName = split[1]+"," + split[5] +","+ split[6];
                    String roadid = commJson.getString(roadapplication);//路段编号
                    String roaddirection = split[3];//路段方向
                    String serialNumber = split[4];//路段序号
                    double roadlength = Double.parseDouble(split[8]);//路段长度
                    String roadstartendlont = split[9];//路段起始点坐标
                    String kind = split[7].charAt(6)+"";
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("roadid",roadid);
                    jsonObject.put("roadapplication",roadapplication);
                    jsonObject.put("roaddirection",roaddirection);
                    jsonObject.put("roadlength",roadlength);
                    jsonObject.put("roadstartendlont",roadstartendlont);
                    jsonObject.put("roadName",roadName);
                    jsonObject.put("kind",kind);
                    jsonObject.put("serialNumber",serialNumber);
                    list.add(jsonObject);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return list;
    }
}
